//
//  GSStrategyAllTableViewController.m
//  GameSky
//
//  Created by lanou on 16/1/11.
//  Copyright © 2016年 NiRongfei. All rights reserved.
//

#import "GSStrategyAllTableViewController.h"
#import "GSSearchViewController.h"
#import "GSStrategyAllCell.h"
#import "GSStrategyHeaderView.h"

@interface GSStrategyAllTableViewController () <UIScrollViewDelegate>

@property (nonatomic, strong) GSStrategyHeaderView *headerView;

@property (nonatomic, strong) NSMutableArray *listDataArray;
@property (nonatomic, strong) NSArray *letterArray;// 首字母数组

@property (nonatomic, assign) NSInteger pageIndex;

@end

@implementation GSStrategyAllTableViewController

- (NSMutableArray *)listDataArray
{
    if (!_listDataArray) {
        _listDataArray = [NSMutableArray array];
    }
    return _listDataArray;
}

- (NSArray *)letterArray
{
    if (!_letterArray) {
        NSMutableArray *array = [NSMutableArray array];
        for (int i = 0; i < 26; i++) {
            NSString *letter = [NSString stringWithFormat:@"%c",(char)('A' + i)];
            [array addObject:letter];
        }
        _letterArray = array;
    }
    return _letterArray;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.automaticallyAdjustsScrollViewInsets = NO;
    
    // 配置TableView;
    self.tableView.dk_backgroundColorPicker = DKColorWithRGB(0xffffff, 0x343434);
    self.tableView.rowHeight = 120;
    _headerView = [[GSStrategyHeaderView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, 44)];
    [_headerView.searchBtn addTarget:self action:@selector(searchBtnClick:) forControlEvents:(UIControlEventTouchUpInside)];
    self.tableView.tableHeaderView = _headerView;
    [self.tableView registerClass:[GSStrategyAllCell class] forCellReuseIdentifier:@"GSStrategyAllCell"];
    
    // 刷新数据;
    [self refreshData];
}

- (void)searchBtnClick:(UIButton *)button
{
    UINavigationController *naviC = [[UINavigationController alloc] initWithRootViewController:[[GSSearchViewController alloc] init]];
    [self presentViewController:naviC animated:YES completion:nil];
}

- (void)loadDataWithPageIndex:(NSInteger)pageIndex
{
    NSMutableDictionary *paraDict = [NSMutableDictionary dictionary];
    paraDict[@"request"] = @{@"type":@1, @"pageIndex":@(pageIndex), @"pageCount":@"20"};
    [GSNetworkManager requestWithUrlStr:@"http://appapi2.gamersky.com/v2/strategy" paraDict:paraDict method:POST success:^(NSURLResponse *response, NSData *data) {
        if (data) {
            NSDictionary *dataDict = [NSJSONSerialization JSONObjectWithData:data options:(NSJSONReadingMutableContainers) error:nil];
            NSArray *resultArray = dataDict[@"result"];
            
            if (pageIndex == 1) {
                [self.listDataArray removeAllObjects];
            }

            for (NSDictionary *subDict in resultArray) {
                    GSStrategyMainModel *model = [[GSStrategyMainModel alloc] init];
                    [model setValuesForKeysWithDictionary:subDict];
                    [self.listDataArray addObject:model];
            }
            // 结束刷新;
            [self.tableView.mj_header endRefreshing];
            [self.tableView.mj_footer endRefreshing];
            
            // 刷新界面;
            [self.tableView reloadData];
        }
    } failure:^(NSError *error) {
        NSLog(@"%@",error);
    }];
}

/**
 *  数据刷新
 */
- (void)refreshData
{
    // 下拉刷新
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        // 下拉刷新重新加载数据;
        _pageIndex = 1;
        [self loadDataWithPageIndex:_pageIndex];
    }];
    
    // 上拉刷新
    self.tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        // 上拉刷新依次叠加数据;
        _pageIndex += 1;
        [self loadDataWithPageIndex:_pageIndex];
    }];
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return _listDataArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    GSStrategyAllCell *cell = [tableView dequeueReusableCellWithIdentifier:@"GSStrategyAllCell" forIndexPath:indexPath];
    cell.model = _listDataArray[indexPath.row];
    // 关闭单元格选中效果;
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    return cell;
}

// 区头
//- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
//    return self.letterArray[section];
//}

// 右侧分区索引
//- (nullable NSArray<NSString *> *)sectionIndexTitlesForTableView:(UITableView *)tableView {
//    return self.letterArray;
//}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    GSStrategyMainModel *model = _listDataArray[indexPath.row];
    if ([_delegate respondsToSelector:@selector(setStrategyDetailViewWithModel:)]) {
        [_delegate setStrategyDetailViewWithModel:model];
    }
}

/**
 *  根据ScrollView纵向偏移量弹出搜索框;
 */
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    if (scrollView.contentOffset.y < -22 && scrollView.contentOffset.y > -44) {
        [scrollView setContentOffset:CGPointMake(0, -44)];
    }
}

/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/

/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
    } else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
}
*/

/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
}
*/

/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
